#include "SimpleRenderApp.h"

#include <sora.h>
#include "SRSceneNodeVisitor.h"
#include "SRScene.h"
#include "SRResource.h"
#include "SRLight.h"

using namespace sora;

SimpleRenderApp::SimpleRenderApp()
	: tex_(NULL)
{
	init();
}

SimpleRenderApp::~SimpleRenderApp()
{
	deinit();
}

void SimpleRenderApp::init()
{
	//test용 texture 만들기
	tex_ = NULL;
	tex_ = new sora::SampleTexture();
	SR_ASSERT(tex_ != NULL);
}

void SimpleRenderApp::deinit()
{
	if(tex_ != NULL)
		delete(tex_);
}

void SimpleRenderApp::render(long tick, int width, int height)
{
	glEnable(GL_CULL_FACE);

	glEnable( GL_DEPTH_TEST );
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

	glViewport(0, 0, width, height);
	glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	//TODO: 1.1용 카메라 구현하기 + scenegraph와 어떻게 결합시킬것인가?
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	float aspect = (float)width / (float)height;
	sora::gles1::gluPerspective( 45.0f, aspect, 0.1f, 100.0f );

	/*
	 //blend
	 {
	 glColor4f(1.0f,1.0f,1.0f,0.5f);			// Full Brightness, 50% Alpha ( NEW )
	 glBlendFunc(GL_SRC_ALPHA,GL_ONE);		// Blending Function For Translucency Based On Source Alpha Value ( NEW )
	 glEnable(GL_BLEND);		// Turn Blending On
	 glDisable(GL_DEPTH_TEST);	// Turn Depth Testing Off
	 glDisable(GL_CULL_FACE);	//blend모드에서 뒷면안그리기가 되면 큐브의 비치는 면을 그리지 않아버린다
	 }
	 */

	sora::SceneNodeGroup root;

	//set transform
	sora::Transformation t1 = sora::Transformation::translate(0, 0, -5);
	root.transformation(t1);

	static GLfloat xrot;
	static GLfloat yrot;
	static GLfloat zrot;

	xrot+=0.3f;
	yrot+=0.2f;
	zrot+=0.4f;

	sora::Transformation t2 = sora::Transformation::rotateX(xrot);
	root.transformation(t2);
	sora::Transformation t3 = sora::Transformation::rotateY(yrot);
	root.transformation(t3);
	sora::Transformation t4 = sora::Transformation::rotateZ(zrot);
	root.transformation(t4);

	//set light
	matsu::vec4 ambient(0.5f, 0.5f, 0.5f, 1.0f);
	matsu::vec4 diffuse(1.0f, 1.0f, 1.0f, 1.0f);
	matsu::vec3 lightPos(0.0f, 0.0f, 2.0f);

	const sora::Light ambientLight = sora::Light::ambient(ambient);
	const sora::Light diffuseLight = sora::Light::diffuse(diffuse, lightPos);
	root.addChild(new sora::LightNode(ambientLight));
	root.addChild(new sora::LightNode(diffuseLight));

	//create model 
	matsu::vec4 color(0.5, 0, 0.5, 1);
	sora::ModelPtr m1 = sora::ModelLoader().loader().loadSolidTeapot(2, color);
	root.addChild(new sora::ModelNode(m1));

	//bounding box
	sora::ModelPtr m2 = sora::ModelLoader().loader().loadBoundingBox(m1);
	root.addChild(new sora::ModelNode(m2));

	//axis
	sora::ModelPtr m3 = sora::ModelLoader().loader().loadWireAxis(3);
	root.addChild(new sora::ModelNode(m3));

	//render
	sora::GLES1Renderer renderer;
	renderer.render(&root);
}
